<?php

namespace App\Http\Controllers\Chat\Api;

use App\Http\Controllers\Chat\BaseController;
use App\Models\Api\User;
use App\Traits\ApiResponseTrait;
use Illuminate\Http\Request;

class RegisterController extends BaseController
{
    public function index(Request $request): \Illuminate\Http\JsonResponse
    {
        $data = $request->all();
        try {
            if(empty($data['user_name'])) {
                return ApiResponseTrait::error('请输入用户名');
            }
            if(empty($data['password'])) {
                return ApiResponseTrait::error('请输入密码');
            }

            $userInfo = User::whereUserName($data['user_name'])->first();
            if(!empty($userInfo->id)){
                return ApiResponseTrait::error('用户名已存在，请换个注册');
            }

            $status = User::create([
                'user_name' => $data['user_name'],
                'password' => password_hash($data['password'], PASSWORD_BCRYPT, ['cost' => 12]),
                'status' => User::STATUS_ON
            ]);
            if ($status === false) {
                return ApiResponseTrait::error('用户注册失败，请稍后重试');
            }

            return ApiResponseTrait::success([],'用户注册成功');
        } catch (\Exception $exception) {
            return ApiResponseTrait::error($exception->getMessage());
        }
    }
}
